//
//  OosContactParser.m
//  Oos4ios
//
//  Created by Pablo Gonzalez on 3/29/11.
//

#import "OosContactFeedParser.h"
#import "../Atom/Feeds/OosContactFeed.h"
#import "../Atom/Entries/OosContactEntry.h"
#import <oos4ios/Model/OosUser.h>
#import <oos4ios/Model/OosMe.h>
#import <oos4ios/Oos4ios.h>
#import <oos4ios/Model/OosAvatarImage.h>

@implementation OosContactFeedParser

static OosContactFeedParser* instance;

+ (OosContactFeedParser *) instance
{
	if (!instance) {
		instance = [[OosContactFeedParser alloc] init];
	}
	return instance;
}

- (NSArray *) parseFeed:(OosFeed *)feed
{
	OosContactFeed *contactFeed = (OosContactFeed *) feed;
	
	NSMutableArray *results = [NSMutableArray array];
	
	OosUser *contact;
	
	OosAvatarImage *avatar;
	NSDate *updatedDate;
    
    NSString *identifier = [feed identifier];
    NSString *slug = [[identifier componentsSeparatedByString:@"/"] lastObject];
    
    OosUser *user = [OosUser userFromSlug:slug];
	
	for (OosContactEntry *entry in [contactFeed entries]) {
		updatedDate = [entry.updatedDate date];
		contact = [OosUser userFromSlug: [entry.slug stringValue]];
		if ([contact isPreviousTo:updatedDate]) {
			NSString *avatarUrl = [entry avatarUrl];
			avatar = [OosAvatarImage avatarFromPath:avatarUrl];
			contact.avatar = avatar;
			contact.updated = updatedDate;
			contact.nick = [entry.title stringValue];
            [user.contacts addObject:contact];
		}
		[results addObject: contact];
	}
	return results;
}

@end
